package com.yune.activity.service;


import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.yune.R;
import com.yune.activity.App;
import com.yune.activity.login.LoginActivity;
import com.yune.bean.SongBean;
import com.yune.utils.NetWorkCallback;
import com.yune.utils.Network;
import com.yune.utils.Utils;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PlayService extends Service {
    private static final String TAG = "emmmmmmm";
    private ServiceBroadcastReceiver receiver;
    public static MediaPlayer mp;
    private boolean nextoneLoop=false;
    private RemoteViews remoteViews;
    private Notification customNotification;
    private SongBean songMsg;
    private final Timer timer = new Timer(true);
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        remoteViews= new RemoteViews(getPackageName(), R.layout.notification);
        initBroadcastReceiver();
        initMediaPlayer();
        initTimer();
    }
    private void initTimer() {
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (mp!=null&&mp.isPlaying()){
                    Intent intent1 = new Intent();
                    intent1.setAction("musicFrgamentReceiver");
                    intent1.putExtra("cmd","playingProgress");
                    intent1.putExtra("progress",mp.getCurrentPosition());
                    intent1.putExtra("fromWeb",songMsg.fromWeb);
                    sendBroadcast(intent1);
                }
            }
        }, 1000, 1000);
    }
    private void initMediaPlayer() {
        if (mp==null){
            mp=new MediaPlayer();
        }
        mp.reset();
        mp.setOnCompletionListener(mp -> {
            if (!mp.isLooping()){//是列表循环就播放下一首
                nextsong();
            }
        });
    }
    private void initBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        //接收界面的歌曲操作命令
        intentFilter.addAction("serviceReceiver");
        //接收远程布局的命令
        intentFilter.addAction("notification_remove");
        intentFilter.addAction("navigation_next");
        intentFilter.addAction("navigation_controller");
        intentFilter.addAction("navigation_last");
        receiver= new ServiceBroadcastReceiver();
        registerReceiver(receiver,intentFilter);
    }
    public interface newPlayCall{
        void call();
    }
    public void newPlay(Intent data, newPlayCall call){
        try {
            if (mp.isPlaying()){ mp.stop(); }
            mp.reset();
            mp.setDataSource(data.getStringExtra("songUrl"));
            mp.setOnPreparedListener(m -> {
                m.start();
                addToHistory(data);
                sendNotification(data);
                if (call!=null){ call.call(); }
            });
            mp.prepareAsync();
            mp.setLooping(nextoneLoop);
        }catch (Exception ignore){}
    }
    private void sendNotification(Intent data) {
        remoteViews.setOnClickPendingIntent(R.id.notification_remove, Utils.getPIntent(this,"notification_remove"));
        remoteViews.setOnClickPendingIntent(R.id.navigation_next, Utils.getPIntent(this,"navigation_next"));
        remoteViews.setOnClickPendingIntent(R.id.navigation_controller, Utils.getPIntent(this,"navigation_controller"));
        remoteViews.setOnClickPendingIntent(R.id.navigation_last, Utils.getPIntent(this,"navigation_last"));
        remoteViews.setTextViewText(R.id.notification_name,data.getStringExtra("songName"));
        remoteViews.setTextViewText(R.id.notification_singer,data.getStringExtra("singer"));
        ImageLoader.getInstance().loadImage(data.getStringExtra("picture"), new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) { }
            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                customNotification = new NotificationCompat.Builder(PlayService.this, "CHANNEL_YUYIN_ID").setSmallIcon(R.drawable.ic_launcher_background).setCustomBigContentView(remoteViews).build();
                customNotification.flags= Notification.FLAG_ONGOING_EVENT;
                NotificationManagerCompat.from(PlayService.this).notify(1023, customNotification);
            }
            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                remoteViews.setImageViewBitmap(R.id.notification_img,loadedImage);
                customNotification = new NotificationCompat.Builder(PlayService.this, "CHANNEL_YUYIN_ID").setSmallIcon(R.drawable.ic_launcher_background).setContentTitle("余音").setSubText("正在播放:"+data.getStringExtra("songName")+"-"+data.getStringExtra("singer")).setCustomBigContentView(remoteViews).build();
                customNotification.flags=Notification.FLAG_ONGOING_EVENT;
                NotificationManagerCompat.from(PlayService.this).notify(1023, customNotification);
            }
            @Override
            public void onLoadingCancelled(String imageUri, View view) { }
        });
    }
    private void addToHistory(Intent data) {
        if (data.getBooleanExtra("fromWeb",false)&&!data.getStringExtra("ifAddedOid").equals("")){
            try {
                JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg",""));
                String url="https://api2.bmob.cn/1/classes/history?where=" + URLEncoder.encode("{\"userObjectId\":\""+loginMsg.getString("objectId")+"\",\"songObjectId\":\""+data.getStringExtra("ifAddedOid")+"\"}");
                Network.get( url, res -> {
                    try {
                        JSONObject result=new JSONObject(res);
                        if (result.isNull("error")){//有东西，不一定有该歌
                            if ( result.getJSONArray("results").length()!=0){//有这项删了再加
                                Network.delete("https://api2.bmob.cn/1/classes/history/" + result.getJSONArray("results").getJSONObject(0).getString("objectId"), res1 -> {
                                    JSONObject jo=new JSONObject();
                                    jo.put("songObjectId",data.getStringExtra("ifAddedOid"));
                                    jo.put("userObjectId",loginMsg.getString("objectId"));
                                    Network.post(jo,"https://api2.bmob.cn/1/classes/history",null);
                                });
                            }else{//没有这项直接加
                                JSONObject jo=new JSONObject();
                                jo.put("songObjectId",data.getStringExtra("ifAddedOid"));
                                jo.put("userObjectId",loginMsg.getString("objectId"));
                                Network.post(jo,"https://api2.bmob.cn/1/classes/history",null);
                            }
                        }else{//没有直接加
                            JSONObject jo=new JSONObject();
                            jo.put("songObjectId",data.getStringExtra("ifAddedOid"));
                            jo.put("userObjectId",loginMsg.getString("objectId"));
                            Network.post(jo,"https://api2.bmob.cn/1/classes/history",null);
                        }
                    } catch (JSONException ignored) { }
                });
            } catch (JSONException ignored) { }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        timer.cancel();
        mp.release();
    }
    //播放或暂停歌曲
    public void pause() {
        if (mp!=null){
            if (mp.isPlaying()) {
                mp.pause();
            }
        }
    }
    public void play(){
        if (mp!=null){
            mp.start();
        }
    }
    private void backState() {
        if (songMsg!=null) {
            Intent intent1 = new Intent();
            intent1.setAction("musicFrgamentReceiver");
            intent1.putExtra("cmd","backStatus");
            intent1.putExtra("songUrl",songMsg.songUrl);
            intent1.putExtra("songName",songMsg.songName);
            intent1.putExtra("singer",songMsg.singer);
            intent1.putExtra("picture",songMsg.picture);
            intent1.putExtra("songId",songMsg.songId);
            intent1.putExtra("fromWeb",songMsg.fromWeb);
            intent1.putExtra("ifAddedOid",songMsg.ifAddedOid);
            if (mp!=null&&mp.isPlaying()){
                intent1.putExtra("isPlaying",mp.isPlaying());
                intent1.putExtra("duration",mp.getDuration());
            }
            sendBroadcast(intent1);
        }
    }
    private void nextsong() {
        try {
            JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg", ""));
            String url="https://api2.bmob.cn/1/classes/playList?order=-createdAt&where=" + URLEncoder.encode("{\"userObjectId\":\""+loginMsg.getString("objectId")+"\"}");
            Network.get(url, res -> {
                JSONArray playlist = new JSONObject(res).getJSONArray("results");
                if (songMsg!=null&&songMsg.fromWeb){
                    if (playlist.length()>0){
                        boolean find=false;
                        int findId=0;
                        for (int i = 0; i < playlist.length(); i++) {
                            if (songMsg.ifAddedOid.equals(playlist.getJSONObject(i).getString("songObjectId"))){
                                find=true;
                                findId=i;
                                break;
                            }
                        }
                        if (find){
                            if (playlist.length()-1==findId){//判断这一个是不是最后一个
                                Log.i(TAG, "nextsong: 已经是最后一首了，播放第一首");
                                newPlay2(playlist.getJSONObject(0).getString("songObjectId"));
                            }else{
                             newPlay2(playlist.getJSONObject(findId+1).getString("songObjectId"));
                            }
                        }else{
                           newPlay2(playlist.getJSONObject(0).getString("songObjectId"));
                        }
                    }
                }else {
                    if(playlist.length()>0){//没找到，就播放第一首
                        newPlay2(playlist.getJSONObject(0).getString("songObjectId"));
                    }
                }
            });
        } catch (JSONException ignored) { }
    }
    private void newPlay2(String songOid) {
        if (!songOid.equals("")) {
            Network.get("https://api2.bmob.cn/1/classes/song/"+songOid, res -> {
                JSONObject song = new JSONObject(res);
                Intent intent = new Intent();
                intent.setAction("serviceReceiver");
                intent.putExtra("cmd","newPlay");
                intent.putExtra("songName",song.getString("songName"));
                intent.putExtra("singer",song.getString("singer"));
                intent.putExtra("picture",song.getString("picture"));
                intent.putExtra("songId",song.getString("songId"));
                intent.putExtra("fromWeb",true);
                intent.putExtra("ifAddedOid",song.getString("objectId"));
                Network.callApi("https://autumnfish.cn/song/url?id=" + new JSONObject(res).getString("songId"), new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {}
                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        try {
                            assert response.body() != null;
                            intent.putExtra("songUrl",new JSONObject(response.body().string()).getJSONArray("data").getJSONObject(0).getString("url"));
                            sendBroadcast(intent);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
            });
        }
    }
    private void lastsong() {
        try {
            JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg", ""));
            String url="https://api2.bmob.cn/1/classes/playList?order=-createdAt&where=" + URLEncoder.encode("{\"userObjectId\":\""+loginMsg.getString("objectId")+"\"}");
            Network.get(url, res -> {
                JSONArray playlist = new JSONObject(res).getJSONArray("results");
                if (songMsg!=null&&songMsg.fromWeb){
                    if (playlist.length()>0){
                        boolean find=false;
                        int findId=0;
                        for (int i = 0; i < playlist.length(); i++) {
                            if (songMsg.ifAddedOid.equals(playlist.getJSONObject(i).getString("songObjectId"))){
                                find=true;
                                findId=i;
                                break;
                            }
                        }
                        if (find){
                            if (findId==0){
                                Log.i(TAG, "lastsong: 已经是第一首了，播放最后一首");
                                newPlay2(playlist.getJSONObject(playlist.length()-1).getString("songObjectId"));
                            }else{
                             newPlay2(playlist.getJSONObject(findId-1).getString("songObjectId"));
                            }
                        }else{
                           newPlay2(playlist.getJSONObject(0).getString("songObjectId"));
                        }
                    }
                }else {
                    if(playlist.length()>0){
                        newPlay2(playlist.getJSONObject(0).getString("songObjectId"));
                    }
                }
            });
        } catch (JSONException ignored) { }
    }
    class ServiceBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("navigation_next")){
                nextsong();
            }
            if (intent.getAction().equals("navigation_controller")){
                if (mp.isPlaying()){
                    mp.pause();
                    remoteViews.setImageViewResource(R.id.navigation_controller,R.drawable.play);
                }else {
                    play();
                    remoteViews.setImageViewResource(R.id.navigation_controller,R.drawable.pause);
                }
                backState();
                NotificationManagerCompat.from(PlayService.this).notify(1023,customNotification);
            }
            if (intent.getAction().equals("navigation_last")){
                lastsong();
            }
            if (intent.getAction().equals("notification_remove")){
                NotificationManagerCompat.from(PlayService.this).cancel(1023);
            }
            if (intent.getAction().equals("serviceReceiver")){
                String cmd=intent.getStringExtra("cmd");
                if (cmd!=null){
                    if (cmd.equals("newPlay")){
                        songMsg=new SongBean(intent.getStringExtra("songName"), intent.getStringExtra("singer"), intent.getStringExtra("picture") ,intent.getStringExtra("songId"),intent.getStringExtra("songUrl"),intent.getBooleanExtra("fromWeb",false),intent.getStringExtra("ifAddedOid"));
                        newPlay(intent, PlayService.this::backState);
                    }
                    if (cmd.equals("pause")){
                        pause();
                        remoteViews.setImageViewResource(R.id.navigation_controller,R.drawable.play);
                        NotificationManagerCompat.from(context).notify(1023,customNotification);
                        backState();
                    }
                    if (cmd.equals("play")){
                        play();
                        remoteViews.setImageViewResource(R.id.navigation_controller,R.drawable.pause);
                        NotificationManagerCompat.from(context).notify(1023,customNotification);
                        backState();
                    }
                    if (cmd.equals("getPlayStatus")){
                        backState();
                    }
                    if (cmd.equals("seekTo")){
                        mp.seekTo(intent.getIntExtra("progress",0));
                    }
                    if (cmd.equals("single_loop")){
                        nextoneLoop=true;
                        if (mp!=null){
                            mp.setLooping(true);
                        }
                    }
                    if (cmd.equals("not_single_loop")){
                        nextoneLoop=false;
                        if (mp!=null){
                            mp.setLooping(false);
                        }
                    }
                    if (cmd.equals("nextsong")){
                        nextsong();
                    }
                    if (cmd.equals("lastsong")){
                        lastsong();
                    }
                }

            }
        }
    }
}
